<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>产品管理页面调试</title>
    <style>
        body { font-family: Arial, sans-serif; margin: 20px; }
        .container { max-width: 1200px; margin: 0 auto; }
        .section { margin: 20px 0; padding: 15px; border: 1px solid #ddd; border-radius: 5px; }
        .debug-info { background: #f5f5f5; padding: 10px; margin: 10px 0; border-radius: 3px; }
        select, button { padding: 8px; margin: 5px; }
        .product-list { display: grid; grid-template-columns: repeat(auto-fill, minmax(300px, 1fr)); gap: 15px; margin-top: 15px; }
        .product-card { border: 1px solid #ddd; padding: 15px; border-radius: 5px; }
        .loading { color: #666; font-style: italic; }
        .error { color: red; background: #ffe6e6; padding: 10px; border-radius: 3px; }
    </style>
</head>
<body>
    <div class="container">
        <h1>产品管理页面过滤调试</h1>
        
        <div class="section">
            <h2>🔍 过滤器控制</h2>
            <div>
                <label>产品类型: </label>
                <select id="productTypeSelect">
                    <option value="">全部类型</option>
                </select>
                <button onclick="loadProducts()">手动刷新</button>
                <button onclick="clearDebugInfo()">清空日志</button>
            </div>
            <div class="debug-info">
                <strong>当前选择:</strong> <span id="currentSelection">无</span><br>
                <strong>API URL:</strong> <span id="currentApiUrl">-</span>
            </div>
        </div>

        <div class="section">
            <h2>📊 调试信息</h2>
            <div id="debugInfo" class="debug-info">正在初始化...</div>
        </div>

        <div class="section">
            <h2>📦 产品列表</h2>
            <div id="productCount">产品数量: -</div>
            <div id="productList" class="product-list">
                <div class="loading">正在加载...</div>
            </div>
        </div>
    </div>

    <script>
        let productTypes = [];
        let allProducts = [];
        
        function log(message) {
            const debugInfo = document.getElementById('debugInfo');
            const timestamp = new Date().toLocaleTimeString();
            debugInfo.innerHTML += `<div>[${timestamp}] ${message}</div>`;
            console.log(`[${timestamp}] ${message}`);
        }

        function clearDebugInfo() {
            document.getElementById('debugInfo').innerHTML = '';
        }

        async function loadProductTypes() {
            try {
                log('🔄 加载产品类型...');
                const response = await fetch('/apis/content.halo.run/v1alpha1/product-types');
                
                if (!response.ok) {
                    throw new Error(`HTTP ${response.status}: ${response.statusText}`);
                }
                
                const data = await response.json();
                productTypes = data.items || [];
                
                log(`✅ 成功加载 ${productTypes.length} 个产品类型`);
                
                // 填充下拉框
                const select = document.getElementById('productTypeSelect');
                select.innerHTML = '<option value="">全部类型</option>';
                
                productTypes.forEach(type => {
                    const option = document.createElement('option');
                    option.value = type.metadata.name;
                    option.textContent = type.spec.displayName;
                    select.appendChild(option);
                });
                
                log(`📋 产品类型列表: ${productTypes.map(t => t.spec.displayName).join(', ')}`);
                
            } catch (error) {
                log(`❌ 加载产品类型失败: ${error.message}`);
                document.getElementById('productList').innerHTML = `<div class="error">无法加载产品类型: ${error.message}</div>`;
            }
        }

        async function loadProducts() {
            try {
                const selectedType = document.getElementById('productTypeSelect').value;
                document.getElementById('currentSelection').textContent = selectedType || '全部类型';
                
                let apiUrl = '/apis/content.halo.run/v1alpha1/products?page=1&size=100';
                if (selectedType) {
                    apiUrl += `&productTypeRef=${encodeURIComponent(selectedType)}`;
                }
                
                document.getElementById('currentApiUrl').textContent = apiUrl;
                log(`🔄 加载产品... API: ${apiUrl}`);
                
                document.getElementById('productList').innerHTML = '<div class="loading">正在加载...</div>';
                
                const response = await fetch(apiUrl);
                
                if (!response.ok) {
                    throw new Error(`HTTP ${response.status}: ${response.statusText}`);
                }
                
                const data = await response.json();
                allProducts = data.items || [];
                
                log(`✅ API 返回 ${allProducts.length} 个产品`);
                document.getElementById('productCount').textContent = `产品数量: ${allProducts.length}`;
                
                if (selectedType) {
                    const filtered = allProducts.filter(p => p.spec.productTypeRef === selectedType);
                    log(`🔍 过滤后产品数量: ${filtered.length}`);
                    
                    if (allProducts.length > 0 && filtered.length === 0) {
                        log(`⚠️ 警告: API返回了产品但过滤后为空，可能是productTypeRef参数未生效`);
                    }
                }
                
                displayProducts(allProducts);
                
            } catch (error) {
                log(`❌ 加载产品失败: ${error.message}`);
                document.getElementById('productList').innerHTML = `<div class="error">无法加载产品: ${error.message}</div>`;
            }
        }

        function displayProducts(products) {
            const container = document.getElementById('productList');
            
            if (products.length === 0) {
                container.innerHTML = '<div>没有找到产品</div>';
                return;
            }
            
            container.innerHTML = products.map(product => `
                <div class="product-card">
                    <h3>${product.spec.displayName}</h3>
                    <p><strong>产品类型引用:</strong> ${product.spec.productTypeRef}</p>
                    <p><strong>价格:</strong> ${product.spec.price ? '¥' + product.spec.price.toFixed(2) : '未设置'}</p>
                    <p><strong>状态:</strong> ${product.spec.published ? '已发布' : '未发布'}</p>
                    <p><strong>描述:</strong> ${product.spec.description || '无描述'}</p>
                    <small><strong>ID:</strong> ${product.metadata.name}</small>
                </div>
            `).join('');
        }

        // 监听下拉框变化
        document.getElementById('productTypeSelect').addEventListener('change', function() {
            const selectedType = this.value;
            log(`🎯 产品类型选择变更: ${selectedType || '全部类型'}`);
            loadProducts();
        });

        // 初始化
        document.addEventListener('DOMContentLoaded', function() {
            log('🚀 开始初始化...');
            loadProductTypes().then(() => {
                loadProducts();
            });
        });
    </script>
</body>
</html>